import json
import uuid

import redis
from dashscope import Generation
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from boss import settings

# Create your views here.

# Redis连接
redis_client = redis.Redis(
    host=settings.REDIS_CONFIG['host'],
    port=settings.REDIS_CONFIG['port'],
    db=settings.REDIS_CONFIG['db'],
    decode_responses=True,
    encoding='utf-8'
)

#多轮对话视图类
class  MutChatAPIView(APIView):
    def post(self, request):
        conversation_id = request.data.get('conversation_id')
        message = request.data.get('message')
        if not message:
            return Response({'error': '消息不能为空'}, status=400)
        if not conversation_id:
            conversation_id,messages=str(uuid.uuid4()),[]
        else:
            history=redis_client.get(f"qa:conversation:{conversation_id}")
            messages=json.loads(history) if history else []
        messages.append({'role': 'user', 'content': message})
        try:
            response = Generation.call(
                api_key="",
                model="qwen-plus",
                messages=messages,
                result_format="message",
            )
            assistant_message=response.output.choices[0].message.content
            messages.append({"role": "assistant", "content": assistant_message})
            redis_client.setex(f"qa:conversation:{conversation_id}",86400*7,json.dumps(messages))
            return Response({
                'conversation_id': conversation_id,
                "answer": assistant_message,
                'message': assistant_message
            })
        except Exception as e:
            # 确保错误信息使用UTF-8编码，避免emoji字符导致的编码问题
            try:
                error_msg = str(e).encode('utf-8', errors='ignore').decode('utf-8')
            except UnicodeError:
                error_msg = "系统内部错误"
            return Response({'error': error_msg}, status=500)


#创建新对话
class CreateConversationView(APIView):
    def post(self, request):
        conversation_id = str(uuid.uuid4())
        title = request.data.get('title')
        if not title:
            return Response({'error': '对话标题不能为空'}, status=400)
        session_info={
            "title": title,
            "conversation_id": conversation_id,
            "created_at": str(uuid.uuid4())[:8]
        }
        redis_client.setex(f"qa:session:{conversation_id}",86400*7,json.dumps(session_info))
        return Response({
            'conversation_id': conversation_id,
            'title': title
        })


#获取对话历史
class GetConversationHistoryView(APIView):
    def get(self, request, conversation_id):
        history = redis_client.get(f"qa:conversation:{conversation_id}")
        session_info = redis_client.get(f"qa:session:{conversation_id}")
        if not history:
            return Response({'error': '对话不存在'}, status=404)
        messages = json.loads(history)
        session_data = json.loads(session_info) if session_info else None
        return Response({
            'conversation_id': conversation_id,
            'title': session_data,
            'messages': messages
        })




#获取对话列表
class GetConversationListView(APIView):
    def get(self, request):
        pattern ="qa:session:*"
        keys=redis_client.keys(pattern)
        conversations=[]
        for key in keys:
            session_data=redis_client.get(key)
            if session_data:
             session_info=json.loads(session_data)
             conversations.append(session_info)
        return Response({
            'conversations': conversations,
            "total": len(conversations)
        })





